<?php
namespace Todo\Service;
use Todo\Util\ArrayUtil;

/**
 * Created by PhpStorm.
 * User: yepanpan
 * Date: 2016/8/8
 * Time: 17:08
 */
class UserService extends BaseService
{
    private static $__INSTANCE = null;

    public static function getInstance(){
        if(!self::$__INSTANCE) self::$__INSTANCE = new UserService();

        return self::$__INSTANCE;
    }

    /**
     * 重置一个用户的密码，默认是8个8
     * @param int $userId 用户ID
     * @param string $password 密码
     * @return bool
     */
    public function resetPassword($userId, $password=''){
        $userModel = D('Todo/Sys/User');
        $userInfo = $userModel->keyFind($userId);
        if(!$password) $password = C('DEFAULT_PASSWORD');
        $userInfo['password'] = LoginService::getInstance()->encrypt($password, $userInfo['salt']);
        return $userModel->save($userInfo);
    }

    /**
     * 更新用户信息
     * @param int $userId 用户ID
     * @param array $post 提交的用户信息
     * @return bool
     */
    public function updateInfo($userId, $post){
        $data = array(
            'nickname' => $post['nickname'],
            'email' => $post['email'],
            'mobile' => $post['mobile']
        );
        $userModel = D('Todo/Sys/User');
        $newpassword = $post['newpassword'];
        if($newpassword){
            if($newpassword != $post['repassword']) {
                $this->setError("新密码和确认密码不一致!");
                return false;
            }
            $userInfo = $userModel->keyFind($userId);
            $data['password'] = LoginService::getInstance()->encrypt($newpassword, $userInfo['salt']);
        }

        return $userModel->where(array('id'=>$userId))->save($data);
    }

    /**
     * 查询一个用户的角色
     * @param $userId 用户ID
     * @param bool $onlyIds 返回逗号隔开的角色ID字符串
     * @return bool|string|array
     */
    public function getUserRole($userId, $onlyIds=false){
        $list = D('Todo/Sys/UserRole')->where(array('user_id'=>$userId))->select();
        if(!$list) return false;

        $list = ArrayUtil::getColumn($list, 'role_id');
        if($onlyIds) return implode(',', $list);
        return $list;
    }

    /**
     * 查询用户的菜单
     * @param int $userId 用户ID
     * @param int|bool $appId=true 应用ID,如果为true，即为全部菜单
     * @return array
     */
    public function getUserMenu($userId, $appId=true){
        $key = 'user_menu_'. $userId.'_'.($appId === true ? 'all' : $appId);
        $menuList = S($key);
        if($menuList) return $menuList;

        if(LoginService::getInstance()->checkSuper($userId)){
            $sql = 'SELECT m.* FROM sys_menu m ';
            if($appId !== true) $sql .= ' WHERE app_id='.$appId;
        }else{
            $roles = S('user_role_ids_'. $userId);
            if(!$roles) $roles = $this->getUserRole($userId, true);
            S('user_role_ids_'. $userId, $roles);

            $sql = 'SELECT DISTINCT m.* FROM sys_menu m 
              JOIN sys_role_menu rm ON rm.menu_id=m.id
              WHERE rm.role_id in (0,'.$roles.') ';
            if($appId !== true) $sql .= ' AND app_id='.$appId;
        }
        $sql .= ' ORDER BY m.sort ASC';

        $menuList = D('Todo/Sys/User')->query($sql);
        S($key, $menuList);
        return $menuList;
    }

    /** 查询一级分组菜单
     * @param array $menuIds 全部菜单ID
     * @return array
     */
    public function getTopMenu($menuIds){
        if(!$menuIds) return null;
        if(is_array($menuIds)) $menuIds = implode(',', $menuIds);
        $sql = 'SELECT DISTINCT m1.* FROM sys_menu m1
          JOIN sys_menu m ON m.pid=m1.id
          WHERE m.id IN ('. $menuIds. ')';
        return D('Todo/Sys/User')->query($sql);
    }

    /**
     * 验证要导入的用户
     * @param string $number 工号或学号
     * @param string $xm 姓名
     * @param string $identity=null 用户身份，默认为空，系统自动判断
     * @return array|bool
     */
    public function checkImportUser($number, $xm, $identity = null){
        if(!$identity){
            $idenInfo = D('Todo/Sys/UserIdentity')->where(array('param'=>$number))->find();
            if(!$idenInfo){
                return false;
            }
            $map = D('Todo/Sys/Identity')->findAll(true);
            $identity = $map[$idenInfo['iden_id']]['code'];
        }

        $data = array();
        if($identity == 'student'){
            $info = D('Todo/Base/Student')->where(array('number'=>$number))->cache(true)->find();
            if(!$info || $info['name'] != $xm){
                return false;
            }
            $data['user_id'] = $info['user_id'];
            $data['name'] = $info['name'];
        }else if($identity == 'teacher'){
            $info = D('Todo/Base/Teacher')->where(array('number'=>$number))->cache(true)->find();
            if(!$info || $info['name'] != $xm){
                return false;
            }
            $data['user_id'] = $info['user_id'];
            $data['name'] = $info['name'];
        }else{
            $info = D('Todo/Sys/User')->where(array('account'=>$number))->cache(true)->find();
            if(!$info || $info['nickname'] != $xm){
                return false;
            }
            $data['user_id'] = $info['id'];
            $data['name'] = $info['nickname'];
        }
        return $data;
    }

    /**
     * 基于一级缓存的用户查询
     * @param $userId
     * @param bool $field
     */
    public function cacheFindUser($userId, $field=true){
        if(isset(self::$CACHES[$userId])){
            $userInfo = self::$CACHES[$userId];
        }else{
            $userInfo = D('Todo/Sys/User')->keyFind($userId);
            self::$CACHES[$userId][$userId] = $userInfo;
        }
        if(!$userInfo) return null;
        return $field===true ? $userInfo : $userInfo[$field];
    }
}